<template>
    <el-dialog v-model="dialogVisible" title="添加管理员" width="540">
        <el-form :model="formItem" label-width="100">
            <el-form-item label="管理员姓名:">
                <el-input v-model="formItem.name" clearable placeholder="请输入管理员姓名" />
            </el-form-item>
            <el-form-item label="管理员账号:">
                <el-input v-model="formItem.account" clearable placeholder="请输入管理员账号" />
            </el-form-item>
            <el-form-item label="管理员密码:">
                <el-input v-model="formItem.password" clearable placeholder="请输入管理员密码" />
            </el-form-item>
            <el-form-item label="管理员角色:">
                <el-select placeholder="请选择管理员角色" v-model="formItem.roleId">
                    <el-option v-for="item in roleData.rows" :key="item._id" :label="item.name"
                        :value="item._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态:">
                <el-radio-group v-model="formItem.state">
                    <el-radio :value='1'>开启</el-radio>
                    <el-radio :value='0'>关闭</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onConfirm">确认</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { addAdminApi, updateAdminApi } from '@/api/adminManage';
import { useFindData } from '@/composables/findData';
import { ref, watch } from 'vue';
const dialogVisible = ref(false);
const formItem = ref<any>({});
const emit = defineEmits(['getAdmin']);
const openDialog = (item?: object) => {
    if (item) {
        formItem.value = { ...item };
    } else {
        formItem.value = {};
    }
    dialogVisible.value = true;
};
const { roleData, getRoleJoint, } = useFindData();


defineExpose({
    openDialog
})
watch(dialogVisible, () => {
    getRoleJoint();
})



function addAdmin() {
    addAdminApi({
        ...formItem.value,
    }).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '添加管理员数据成功',
            });
            emit('getAdmin');
        } else {
            ElMessage.error(res.message);
        }
    })
}

function updateAdmin() {
    updateAdminApi({
        ...formItem.value,
    }).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '修改管理员数据成功',
            });
            emit('getAdmin')
        } else {
            ElMessage.error(res.message);
        }
    })
}


function onConfirm() {
    if (formItem.value._id) {
        updateAdmin();
    } else {
        addAdmin();
    }
    dialogVisible.value = false;
}
</script>

<style scoped>
.el-input,
.el-select {
    width: 412px;

}
</style>
<style></style>
